package handler

import (
	"hrms-api/model"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

// GetNotices 获取公告列表
func GetNotices(c *gin.Context) {
	var notices []model.Notice
	if err := model.DB.Find(&notices).Error; err != nil {
		InternalServerError(c, "获取公告列表失败")
		return
	}
	Success(c, notices)
}

// CreateNotice 创建公告
func CreateNotice(c *gin.Context) {
	var notice model.Notice
	if err := c.ShouldBindJSON(&notice); err != nil {
		BadRequest(c, "无效的请求参数")
		return
	}

	if err := model.DB.Create(&notice).Error; err != nil {
		InternalServerError(c, "创建公告失败")
		return
	}
	Success(c, notice)
}

// GetNotice 获取公告详情
func GetNotice(c *gin.Context) {
	id := c.Param("id")
	var notice model.Notice
	if err := model.DB.First(&notice, id).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			NotFound(c, "公告不存在")
		} else {
			InternalServerError(c, "获取公告详情失败")
		}
		return
	}
	Success(c, notice)
}

// UpdateNotice 更新公告
func UpdateNotice(c *gin.Context) {
	id := c.Param("id")
	var notice model.Notice
	if err := model.DB.First(&notice, id).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			NotFound(c, "公告不存在")
		} else {
			InternalServerError(c, "获取公告失败")
		}
		return
	}

	if err := c.ShouldBindJSON(&notice); err != nil {
		BadRequest(c, "无效的请求参数")
		return
	}

	if err := model.DB.Save(&notice).Error; err != nil {
		InternalServerError(c, "更新公告失败")
		return
	}
	Success(c, notice)
}

// DeleteNotice 删除公告
func DeleteNotice(c *gin.Context) {
	id := c.Param("id")
	if err := model.DB.Delete(&model.Notice{}, id).Error; err != nil {
		InternalServerError(c, "删除公告失败")
		return
	}
	Success(c, nil)
}
